import re

from bson import Regex
from fastapi import APIRouter
from pydantic import BaseModel

from items.http_api_response import HTTPApiResponse
from models.ziniao_accounts import ziniao_accounts_model, ZiniaoAccountsItem
from utils.ziniao import ZiNiaoBrowserTools

router = APIRouter(prefix='/ziniao', tags=["紫鸟浏览器"])


class AddAccountItem(BaseModel):
    company: str
    username: str
    password: str
    platform: str


@router.post("/add_account")
async def add_account(item: AddAccountItem):
    ziniao_accounts_model.sync_insert_one(ZiniaoAccountsItem(
        platform=item.platform,
        company=item.company,
        username=item.username,
        password=item.password,
    ))
    return HTTPApiResponse.success(data=None)


def get_regex(value):
    patt = re.compile(value)
    regex = Regex.from_native(patt)
    regex.flags = re.I
    return regex


@router.get("/shop_info")
async def shop_info(platform: str = "", username=""):
    filter = {}
    if platform:
        filter.update({"platform": {"$regex": get_regex(platform)}})
    if username:
        filter.update({"username": {"$regex": get_regex(username)}})
    item = await ziniao_accounts_model.async_find_one(filter)
    zi = ZiNiaoBrowserTools()
    user_info = item.json(include={"company", "username", "password"})
    return HTTPApiResponse.success(data=zi.get_browser_info(user_info))
